﻿
#ifndef ONEUPUTILITY_CG_INCLUDE
#define ONEUPUTILITY_CG_INCLUDE

#include "UnityCG.cginc"
#include "AutoLight.cginc"
#include "Lighting.cginc"


#define BASE_DATA_INPUT \
fixed3 normal:NORMAL; \
fixed3 tangent:TANGENT;\
float4 wpos:TEXCOORD1;

#define BASE_DATA_VERTEX \
o.wpos = mul(unity_ObjectToWorld,v.vertex); \
o.normal = v.normal; \
o.tangent = v.tangent;

#define BASE_DATA_FRAG \
half3 worldNormal = normalize(UnityObjectToWorldNormal(i.normal)); \
half3 worldTangent = normalize(mul(unity_ObjectToWorld,i.tangent)); \
half3 worldLightDir = normalize(UnityWorldSpaceLightDir(i.wpos)); \
half3 worldViewDir = normalize(UnityWorldSpaceViewDir(i.wpos)); \

#define MATRIX_T2W \
half3 worldBiNormal = normalize(cross(worldNormal,worldTangent)) * i.wpos.w; \
float3x3 matrix_t2w = float3x3( \
    worldTangent.x,worldBiNormal.x,worldNormal.x, \
    worldTangent.y,worldBiNormal.y,worldNormal.y, \
    worldTangent.z,worldBiNormal.z,worldNormal.z \
);

inline float3 VertexJitterOffset(float3 vertex, half _JitterDuration,half _JitterSegWidth,half _JitterOffset)
{
    half _OptTime = sin(_Time.w * _JitterDuration);
    half timeToJitter = step(0.99, _OptTime);
    half jitterPosY = vertex.y + _SinTime.y;
    half jitterPosYRange = step(0, jitterPosY) * step(jitterPosY, _JitterSegWidth);
    half offset = jitterPosYRange * _JitterOffset * timeToJitter * _SinTime.y;
    return half3(offset,0,offset);
}

//计算matcap采样坐标，输入归一化的模型空间下的法线和顶点
inline half2 CaculateMatCapUV(half3 normal,float3 vertex)
{
    // https://gameinstitute.qq.com/community/detail/128771
    //乘以逆转置矩阵将normal变换到视空间
    float3 viewnormal = mul(UNITY_MATRIX_IT_MV, normal);
    viewnormal = normalize(viewnormal);
    float3 viewPos = UnityObjectToViewPos(vertex);
    float3 r = reflect(-viewPos, viewnormal);
    float m = 2.0 * sqrt(r.x * r.x + r.y * r.y + (r.z + 1) * (r.z + 1));
    return r.xy / m + 0.5;
}

//计算matcap采样坐标，输入归一化的世界空间下的法线和顶点
inline half2 CaculateMatCapUV1(half3 worldNormal,float4 wpos)
{
    float3 viewDir = -normalize(UnityWorldSpaceViewDir(wpos));
    float3 wr = reflect(viewDir, worldNormal);
    float3 vr = mul(UNITY_MATRIX_V,wr);
    float m = 2.82842712474619 * sqrt(vr.z + 1.0);
    return vr.xy / m + 0.5;
}


#endif